package com.wwwarehouse.resource_center.fragment.information;

import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Parcelable;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.fastjson.JSON;
import com.google.android.flexbox.FlexboxLayout;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.wwwarehouse.common.activity.media.PreviewImageActivity;
import com.wwwarehouse.common.bean.media.UploadType;
import com.wwwarehouse.common.bean.response.CommonClass;
import com.wwwarehouse.common.constant.Constant;
import com.wwwarehouse.common.eventbus_event.BackListenerEvent;
import com.wwwarehouse.common.tools.ConvertUtils;
import com.wwwarehouse.resource_center.R;
import com.wwwarehouse.resource_center.adapter.rules.SelectAppObjAdapter;
import com.wwwarehouse.resource_center.bean.goods.GoodsAttributesBean;
import com.wwwarehouse.resource_center.bean.goods.GoodsSelectLabelBean;
import com.wwwarehouse.resource_center.bean.goods.InfomationBean;
import com.wwwarehouse.resource_center.constant.ResourceConstant;
import com.wwwarehouse.resource_center.fragment.createobject.creategoods.CreateGoodsFragment;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.wwwarehouse.resource_center.constant.ResourceConstant.PATH_H_GOODS;

/**
 * @author Joseph on 2017/9/26.
 *         <p/>
 *         商品详情
 */
@Route(path = PATH_H_GOODS)
public class InfomationGoodsFragment extends CreateGoodsFragment {

    private String itemType;
    private String type;
    private long ukid;
    public static final int QUERY_ITEMORRESOURCE_DETAIL = 1;
    public ArrayList<GoodsSelectLabelBean.ListBean> laberData;  //标签
    public ArrayList<GoodsAttributesBean.ListBean> attrData; //属性
    public String url;
    private String introduction;
    private String beanType;
    private List<InfomationBean.LabelListBean> labelList;
    private List<InfomationBean.AttributeListBean> attributeList;
    private List<InfomationBean.IdentifyListBean> identifyList;
    private int height;
    private int width;

    @Override
    public void setTitle() {
        if (peekFragment() instanceof InfomationGoodsFragment){
            mActivity.setTitle(getString(R.string.Product_details));
        }
    }
    @Override
    protected int getContentId() {
        return R.layout.fragment_create_goods;
    }

    @Override
    protected void loadDatas() {
        mGoodsName.setBackgroundColor(mActivity.getResources().getColor(R.color.white));
        img_name.setVisibility(View.GONE);
        category_item.setVisibility(View.GONE);
        mGoodsCategory.setVisibility(View.GONE);
        elasticScrollView.setOnPullListener(null);
        mGoodsAttribute.setSelected(true);
        mGoodsAttribute.setOnClickListener(this);
        mLLLaber.setVisibility(View.GONE);
        mGoodsPicture.setSelected(true);
        LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) mName.getLayoutParams();
        layoutParams.topMargin = 0;
        mName.setLayoutParams(layoutParams);
        mName.setTextColor(mActivity.getResources().getColor(R.color.common_color_c7_96999e));
    }

    @Override
    public void requestDatas() {
        Bundle arguments = getArguments();
        if (null != arguments) {
            itemType = arguments.getString("itemType");
            type = arguments.getString("type");
            ukid = arguments.getLong("ukid");
        }
        final ViewTreeObserver observer = mLaber.getViewTreeObserver();
        observer.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                observer.removeGlobalOnLayoutListener(this);
                height = mLaber.getHeight();
                width = mLaber.getWidth();
                Log.d("observer",height+"==="+width+"");
            }
        });


        queryItemOrResourceDetail(itemType, type, ukid);
    }

    private void queryItemOrResourceDetail(String itemType, String type, long ukid) {
        Map map = new HashMap();
        map.put("itemType", itemType);
        map.put("type", type);
        map.put("ukid", ukid);
        httpPost(ResourceConstant.QUERY_ITEMORRESOURCE_DETAIL, map, QUERY_ITEMORRESOURCE_DETAIL, true, "加载中……");
    }

    @Override
    public void onSuccess(CommonClass commonClass, int what) {
        switch (what) {
            case QUERY_ITEMORRESOURCE_DETAIL:
                if (TextUtils.equals("0", commonClass.getCode())) {
                    try {
                        InfomationBean bean = JSON.parseObject(commonClass.getData().toString(), InfomationBean.class);
                        mName.setText(bean.getName());
                        mCategory.setText(bean.getType());
                        mDes.setText(bean.getIntroduction());
                        labelList = bean.getLabelList();
                        attributeList = bean.getAttributeList();
//                        beanType = bean.getType();
//                        mCategory.setText(beanType);
                        introduction = bean.getIntroduction();
                        mDes.setText(introduction);
                        mTag.setVisibility(View.GONE);
                        mLLBar.setVisibility(View.VISIBLE);
                        try {
                            url = bean.getMediaList().get(0).getUrl();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        if (TextUtils.isEmpty(url)) {
                            mGoodsPicture.setSelected(true);
                            mLLPic.setVisibility(View.VISIBLE);
                            img_descrip.setText("暂无图片");
                            no_pic.setBackgroundResource(R.drawable.picture_no);
                            img_descrip.setTextColor(mActivity.getResources().getColor(R.color.common_color_c7_96999e));
                        } else {
                            mLLPic.setVisibility(View.GONE);
                            mIvPic.setVisibility(View.VISIBLE);
                            ImageLoader.getInstance().displayImage(url, mIvPic, new ImageLoadingListener() {
                                @Override
                                public void onLoadingStarted(String s, View view) {

                                }

                                @Override
                                public void onLoadingFailed(String s, View view, FailReason failReason) {
                                    mGoodsPicture.setSelected(true);
                                    mLLPic.setVisibility(View.VISIBLE);
                                    img_descrip.setText("图片加载失败");
//                                    LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) img_descrip.getLayoutParams();
//                                    layoutParams.topMargin = 100;
//                                    img_descrip.setLayoutParams(layoutParams);
                                    no_pic.setBackgroundResource(R.drawable.picture_no);
                                    img_descrip.setTextColor(mActivity.getResources().getColor(R.color.common_color_c7_96999e));
                                }

                                @Override
                                public void onLoadingComplete(String s, View view, Bitmap bitmap) {

                                }

                                @Override
                                public void onLoadingCancelled(String s, View view) {

                                }
                            });
                        }
                        try {
                            identifyList = bean.getIdentifyList();
                           if (identifyList.size()>=2){
                               mBarCode.setText(identifyList.get(0).getValue());
                               mSequenceCode.setText(identifyList.get(1).getValue());
                           }else {
                               mBarCode.setText(identifyList.get(0).getValue());
                           }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        laberData = new ArrayList<>();
                        for (int i = 0; i < bean.getLabelList().size(); i++) {

                            GoodsSelectLabelBean.ListBean listBean = new GoodsSelectLabelBean.ListBean();
                            listBean.setLabelName(bean.getLabelList().get(i).getName());
                            laberData.add(listBean);
                        }
                        setLaberc(laberData);

                        attrData = new ArrayList<>();

                        for (int i = 0; i < bean.getAttributeList().size(); i++) {

                            GoodsAttributesBean.ListBean attrBean = new GoodsAttributesBean.ListBean();
                            attrBean.setAttributeName(bean.getAttributeList().get(i).getName());
                            attrBean.setAttributeValue(bean.getAttributeList().get(i).getValue());
                            attrData.add(attrBean);

                        }
                        setAttributes(attrData);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                else {
                    try {
                        toast(commonClass.getMsg());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                break;
        }
    }

    @Override
    public void onEventMainThread(Object event) {
        if (event instanceof BackListenerEvent) {
            popFragment();
        }
    }

    public void setLaberc(ArrayList<GoodsSelectLabelBean.ListBean> data) {
        mLaber.removeAllViews();
        mLLLaber.setVisibility(View.GONE);
        if (data.size() < 6) {
            for (int i = 0; i < data.size(); i++) {
                TextView textView = getTextView();
                textView.setBackgroundResource(R.drawable.laber_bg_selector);
                textView.setTextColor(Color.parseColor("#337CFF"));
                textView.setText(data.get(i).getLabelName());
                textView.setSelected(true);

                mLaber.addView(textView);
            }
            for (int i = 0; i < 6 - data.size(); i++) {
                TextView textView = getTextView();
                textView.setBackgroundResource(R.drawable.laber_bg_selector);
                textView.setSelected(false);
                mLaber.addView(textView);
            }
        } else if (data.size() >= 6) {
            for (int i = 0; i <= 5; i++) {
                TextView textView = new TextView(getContext());
                textView.setWidth(ConvertUtils.dip2px(getContext(), 82));
                textView.setHeight(ConvertUtils.dip2px(getContext(), 26));
                textView.setBackgroundResource(R.drawable.laber_bg_selector);
                textView.setTextColor(Color.parseColor("#337CFF"));
                textView.setTextSize(11);
                textView.setGravity(Gravity.CENTER);
                textView.setMaxLines(1);
                textView.setEllipsize(TextUtils.TruncateAt.END);
                if (i == 5) {
                    textView.setText(R.string.ellipsis);
                } else {
                    textView.setText(data.get(i).getLabelName());
                }
                textView.setSelected(true);
                FlexboxLayout.LayoutParams layoutParams = new FlexboxLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                layoutParams.setMargins(ConvertUtils.dip2px(getContext(), 8), ConvertUtils.dip2px(getContext(), 8), 0, 0);
                textView.setLayoutParams(layoutParams);
                mLaber.addView(textView);
            }

        }
    }
    public TextView getTextView() {
        TextView textView = new TextView(getContext());
        textView.setWidth(ConvertUtils.dip2px(getContext(), 82));
        textView.setHeight(ConvertUtils.dip2px(getContext(), 26));
        textView.setBackgroundResource(R.drawable.laber_bg_selector);
        textView.setMaxLines(1);
        textView.setEllipsize(TextUtils.TruncateAt.END);
        textView.setGravity(Gravity.CENTER);
        textView.setTextSize(12);
        FlexboxLayout.LayoutParams layoutParams = new FlexboxLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        layoutParams.setMargins(ConvertUtils.dip2px(getContext(), 8), ConvertUtils.dip2px(getContext(), 8), 0, 0);
        textView.setLayoutParams(layoutParams);
        return textView;
    }
    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.rel_name) {
            //名称


        } else if (i == R.id.rel_picture) {
            if (null != url) {
                List<UploadType> typeList = new ArrayList<>();
                UploadType  upload = new UploadType();
                upload.setPath("");
                UploadType  uploadType = new UploadType();
                uploadType.setPath(url);
                typeList.add(uploadType);
                typeList.add(upload);
                Bundle bundle = new Bundle();
                bundle.putString(Constant.KEY_PHOTO_VIEW_PREFIX, "http");
                bundle.putSerializable(Constant.KEY_UPLOAD_LIST, (Serializable) typeList);
                startActivity(PreviewImageActivity.class, bundle, false);
            }

        }
//        else if (i == R.id.rel_category) {

            //类目
//            if (null != beanType) {
//                InfomationCategoryNameFragment nameFragment = new InfomationCategoryNameFragment();
//                Bundle bundle = new Bundle();
//                bundle.putString("CategoryName", beanType);
//                nameFragment.setArguments(bundle);
//                pushFragment(nameFragment);
//            }
//        }
        else if (i == R.id.rel_describe) {
            //描述
            if (null != introduction) {
                InfomationDescripFragment descripFragment = new InfomationDescripFragment();
                Bundle bundle = new Bundle();
                bundle.putString("data", introduction);
                bundle.putString("type", "good_descrip");
                bundle.putString("title", getResources().getString(R.string.good_descrip_text));
                descripFragment.setArguments(bundle);
                pushFragment(descripFragment);
            }
        } else if (i == R.id.rel_label) {
            //标签
            if (null != laberData) {
                InfomationShowLabelParentFragment fragment = new InfomationShowLabelParentFragment();
                Bundle bundle = new Bundle();
                bundle.putParcelableArrayList("laberData", laberData);
                bundle.putString("title",getString(R.string.goods_label_name));
                fragment.setArguments(bundle);
                pushFragment(fragment);
            }
        } else if (i == R.id.rel_tag) {
            // 添加标识标签
            if (null != identifyList) {
                InfomationShowLogoBarcodeListChildFragment childFragment = new InfomationShowLogoBarcodeListChildFragment();
                Bundle bundle = new Bundle();
                bundle.putParcelableArrayList("Barcode", (ArrayList<? extends Parcelable>) identifyList);
                childFragment.setArguments(bundle);
                pushFragment(childFragment);
            }
        } else if (i == R.id.rel_attribute) {
            //属性
            if (null != attrData) {
                InfomationShowAttributesParentFragment parentFragment = new InfomationShowAttributesParentFragment();
                Bundle bundle = new Bundle();
                bundle.putParcelableArrayList("attrData", attrData);
                bundle.putString("title",getString(R.string.goods_attr));
                parentFragment.setArguments(bundle);
                pushFragment(parentFragment);
            }
        }
    }

    @Override
    public void onReLoad(int code) {
        queryItemOrResourceDetail(itemType, type, ukid);
    }
}
